home *** CD-ROM | disk | FTP | other *** search
/ Nebula 2 / Nebula Two.iso / NextAnswers / 1436_mixing_objective-C_and_C_code.rtf < prev    next >
Text File  |  1993-11-08  |  2KB  |  58 lines

  1. {\rtf0\ansi{\fonttbl\f0\fnil Times-Roman;\f1\fmodern Courier;\f2\fswiss Helvetica;\f3\fmodern Ohlfs;}
  2. \paperw10880
  3. \paperh8420
  4. \margl120
  5. \margr120
  6. {\colortbl;\red83\green83\blue83;\red82\green82\blue82;}
  7. \pard\tx960\tx1920\tx2880\tx3840\tx4800\tx5760\tx6720\tx7680\tx8640\tx9600\f0\b0\i0\ulnone\fs28\fc0\cf0 Q:  How does one mix C and Objective-C code?  How can one call Objective-C from C?\
  8. \
  9. A:  Just do it!  C functions can freely send Objective-C messages, and Objective-C methods can freely call C functions.   For an example, look at 
  10. \b main()
  11. \b0  of one of the applications in /NextDeveloper/Examples.   \
  12. \
  13. If you place Objective-C code in a ".c" file,  you need to compile the file with the Objective -C option.  The simplest way to do this is to change the ".c" suffix to ".m", and then add the file name under ".m (other)"  in InterfaceBuilder's Project Inspector.    If it's not possible to change the suffix, compile the file using the 
  14. \b -ObjC 
  15. \b0 compiler flag.  \
  16. \
  17. You can place any C code in a ".m" file without any special handling.  The C code needs to extern id's as per regular C scoping rules.\
  18. \
  19. Only within Objective-C methods can you directly access instance variables and the hidden variable "self."  You must pass an object to a C function that needs access to it.   For example, this C function returns the width of a View:\
  20. \
  21.  
  22. \f1\fs24     NXCoord widthOfView(View *self)\
  23.     \{\
  24.         NXRect b;\
  25.         [self getBounds:&b];\
  26.         return b.size.width;\
  27.     \}\
  28.  
  29. \f0\fs28 \
  30. You may access 
  31. \b public
  32. \b0  instance variables like this: \
  33. \
  34.  
  35. \f1\fs24     void setNumber(MyObject *self,int newValue)\
  36.     \{\
  37.         self->number = newValue;\
  38.     \}\
  39.  
  40. \f0\fs28 \
  41. Remember that all instance variables are considered private unless explicitly declared public.  However, within the confines of a class implementation, all instance variables of that class are considered public.  So in the implementation for MyControl (a subclass of Control), you could write a C function to set the tag of a MyControl object like this:\
  42. \
  43.  
  44. \f1\fs24     void setTag(MyControl *self,int newTag)\
  45.     \{\
  46.         self->tag = newTag;\
  47.     \}\
  48. \
  49.  
  50. \f0\fs28 QA27\
  51.  
  52. \pard\tx520\tx1060\tx1600\tx2120\tx2660\tx3200\tx3720\tx4260\tx4800\tx5320\f2\fs24\fc0\cf0 \
  53.  
  54. \f0\fs28 Valid for 1.0, 2.0,
  55. \pard\tx960\tx1920\tx2880\tx3840\tx4800\tx5760\tx6720\tx7680\tx8640\tx9600\fc0\cf0  3.0\
  56. \
  57.  
  58.